/*
 * pwm.c
 * Project 4
 * Nicole Ang (nang1@asu.edu)
 * Bijan Fakhri (bfakhri@asu.edu)
 * CSE 325: Embedded Microprocessor Systems
 * Spring 2013
 */
#include "pwm.h"

void pwm_init(){
	gpio_ta_init(); //set gpio direction to output
	
	//disable register while configuring 
	MCF_PWM_PWME &= ~MCF_PWM_PWME_PWME7;
	
	//low at beginning
	MCF_PWM_PWMPOL &= ~MCF_PWM_PWMPOL_PPOL7;
	
	//set clock SB
	//MCF_PWM_PWMCLK &= ~MCF_PWM_PWMCLK_PCLK7;
	MCF_PWM_PWMCLK |= MCF_PWM_PWMCLK_PCLK7;
	
	//prescaler
	MCF_PWM_PWMPRCLK |= MCF_PWM_PWMPRCLK_PCKB(1);
	//scale B
	MCF_PWM_PWMSCLB = MCF_PWM_PWMSCLB_SCALEB(182);
	
	//left-aligned output
	MCF_PWM_PWMCAE &= ~MCF_PWM_PWMCAE_CAE7;
	
	//counter
	MCF_PWM_PWMCNT7 = MCF_PWM_PWMCNT(10);
	
	//period
	MCF_PWM_PWMPER7 = MCF_PWM_PWMPER_PERIOD(210);
	
	//duty
	MCF_PWM_PWMDTY7 = MCF_PWM_PWMDTY_DUTY(168);
}

void set_frequency(Pitch pitch){
	MCF_PWM_PWME &= ~MCF_PWM_PWME_PWME7; //turn off speaker
	switch(pitch){
	case B3: MCF_PWM_PWMSCLB = MCF_PWM_PWMSCLB_SCALEB(162);
		MCF_PWM_PWMPER7 = MCF_PWM_PWMPER_PERIOD(250);
		MCF_PWM_PWMDTY7 = MCF_PWM_PWMDTY_DUTY(200);
		break;
	case C4: MCF_PWM_PWMSCLB = MCF_PWM_PWMSCLB_SCALEB(195);
		MCF_PWM_PWMPER7 = MCF_PWM_PWMPER_PERIOD(196);
		MCF_PWM_PWMDTY7 = MCF_PWM_PWMDTY_DUTY(157);
		break;
	case D4: MCF_PWM_PWMSCLB = MCF_PWM_PWMSCLB_SCALEB(139);
		MCF_PWM_PWMPER7 = MCF_PWM_PWMPER_PERIOD(245);
		MCF_PWM_PWMDTY7 = MCF_PWM_PWMDTY_DUTY(196);
		break;
	case E4: MCF_PWM_PWMSCLB = MCF_PWM_PWMSCLB_SCALEB(154);
		MCF_PWM_PWMPER7 = MCF_PWM_PWMPER_PERIOD(197);
		MCF_PWM_PWMDTY7 = MCF_PWM_PWMDTY_DUTY(158);
		break;
	case F4: MCF_PWM_PWMSCLB = MCF_PWM_PWMSCLB_SCALEB(249);
		MCF_PWM_PWMPER7 = MCF_PWM_PWMPER_PERIOD(115);
		MCF_PWM_PWMDTY7 = MCF_PWM_PWMDTY_DUTY(92);
		break;
	case G4: MCF_PWM_PWMSCLB = MCF_PWM_PWMSCLB_SCALEB(196);
		MCF_PWM_PWMPER7 = MCF_PWM_PWMPER_PERIOD(130);
		MCF_PWM_PWMDTY7 = MCF_PWM_PWMDTY_DUTY(104);
		break;
	case A4: MCF_PWM_PWMSCLB = MCF_PWM_PWMSCLB_SCALEB(225);
		MCF_PWM_PWMPER7 = MCF_PWM_PWMPER_PERIOD(101);
		MCF_PWM_PWMDTY7 = MCF_PWM_PWMDTY_DUTY(81);
		break;
	case A3: MCF_PWM_PWMSCLB = MCF_PWM_PWMSCLB_SCALEB(184);
		MCF_PWM_PWMPER7 = MCF_PWM_PWMPER_PERIOD(247);
		MCF_PWM_PWMDTY7 = MCF_PWM_PWMDTY_DUTY(198);
		break;
	case pause: MCF_PWM_PWMSCLB = MCF_PWM_PWMSCLB_SCALEB(0);
		MCF_PWM_PWMPER7 = MCF_PWM_PWMPER_PERIOD(0);
		MCF_PWM_PWMDTY7 = MCF_PWM_PWMDTY_DUTY(0);
		break;
	default: break;
	}
	MCF_PWM_PWME |= MCF_PWM_PWME_PWME7; //turn on speaker
}
